import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/assessments.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/knowledgeword.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/widgets/BGExamWidget.dart';
import 'package:ichinesereader/utils/StrUtil.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/widgets/tools/strokAnimator.dart';
import '../../widgets/dialogs/simpleAlertDialog.dart';
import '../common/fireWorks.dart';

class WordCardQuiz extends StatefulWidget {
  WordCardQuiz({this.isFromMyWords, this.readingType, this.bookId, Key? key})
      : super(key: key);
  final bool? isFromMyWords;
  final NanhaiBookReadingTypes? readingType;
  final String? bookId;

  @override
  State<StatefulWidget> createState() => _WordCardQuizState();
}

class _WordCardQuizState extends State<WordCardQuiz> {
  final KnowledgeWordsController controller = Get.find();
  final AssessmentsController assessmentsController = Get.find();
  String title = '';
  String note = '';
  String answer = '';
  bool first = true;
  bool lastPage = false, showHandWriting = true;
  final box = Hive.box('appconfig');
  bool ifNext = false;
  bool firework = false;
  _getAnswer(value) {
    // controller.questions![controller.currWordQuizPage][0].answer = value;
    controller.records.forEach((element) {
      if (element['questionId'].contains(title.substring(1))) {
        // element.update('answer', (value) => value.add(value));
        if (title == 'Option') {
          if (first) {
            element['answer'].add(value);
            first = false;
          }
        } else {
          element['answer'].clear();
          element['answer'].add(value);
        }
      }
    });
    // if (title == 'Option') {
    //   var message = '';
    //   if (value == answer)
    //     message = "Correct answer".tr;
    //   else
    //     message = "Wrong answer".tr;

    //   showGeneralDialog(
    //       context: context,
    //       transitionDuration: Duration(milliseconds: 400),
    //       pageBuilder: (bc, ania, anis) {
    //         return SimpleAlertDialog(
    //           message: message,
    //           title: '',
    //         );
    //       });
    // }
    ifNext = true;
  }

  @override
  Widget build(BuildContext context) {
    bool isTeacherOrSchoolAdmin =
        box.get(CacheManagerKey['nanhairole'].toString()) ==
                Constants.NanhaiRole_Teacher ||
            box.get(CacheManagerKey['nanhairole'].toString()) ==
                Constants.NanhaiRole_SchoolAdmin;
    List<Widget> children = [];
    first = true;
    ifNext = false;

    QuestionItem? questionItem = controller.questions != null &&
            controller.questions!.length > 0 &&
            controller.currWordQuizPage < controller.questions!.length
        ? controller.questions![controller.currWordQuizPage]
        : null;

    if (questionItem != null) {
      title = questionItem.type!;
      answer = questionItem.solution![0];
      if (title == 'vanish') {
        title = 'Match to disappear';
        note = 'MatchDisappearNote';
      } else
        title = StrUtil.capitalize(title);
      if (title == 'Match') {
        note = 'MatchNote';
      }
      children.add(Padding(
          padding: EdgeInsets.only(left: 20, right: 20),
          child: BGExamWidget(
              questionItem: questionItem,
              getAnswer: _getAnswer,
              isShowJudge: true,
              mode: BGExamWidgetMode.Test)));
    }

    if (controller.currWordQuizPage >= controller.questions!.length) {
      // int index = controller.currWordQuizPage - controller.questions!.length;
      ifNext = true;
      if (controller.handWriting != null && showHandWriting) {
        title = "Hand Writing Words".tr;
        note = "handwriteNote".tr;
        List<TextButton> texts = [];
        controller.handWriting!.forEach((element) {
          texts.add(
            TextButton(
              onPressed: () {
                Get.to(() => StrokeAnimator(
                      characters: element,
                    ));
              },
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Get.isDarkMode
                      ? Get.theme.primaryColor
                      : Get.theme.primaryColorDark.withOpacity(0.6),
                ),
                width: 72.0,
                height: 72.0,
                padding: EdgeInsets.all(12.0),
                child: Text(
                  element,
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 36,
                  ),
                ),
              ),
            ),
          );
        });

        Widget widget = Container(
          margin: EdgeInsets.only(top: 150.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: texts,
          ),
        );
        children.add(widget);
        showHandWriting = false;
      } else {
        title = "Good Job".tr;
        lastPage = true;
        setState(() {
          firework = true;
        });
        if (controller.handWriting != null && !isTeacherOrSchoolAdmin) {
          assessmentsController
              .submitReportRecord(controller.records, controller.bookCode)
              .then((statusMessage) {
            if (statusMessage.status == 1000) {
              // setState(() {
              //   firework = true;
              // });

              if (statusMessage.result != null) {
                Map<String, dynamic> mapData = statusMessage.result;
                if (widget.bookId != null &&
                    widget.readingType != null &&
                    mapData['id'] != null) {
                  final BooksController booksController = Get.find();
                  booksController.updateBookKnowledgeItemStatus(
                      widget.readingType!,
                      NanhaiBookKnowledgeTypes.wordcard,
                      widget.bookId!,
                      mapData['id']);
                }
              }
            } else {
              //可增加不成功的信息提示
            }
          });
        }
      }
    }
    if (!lastPage) {
      children.add(
        Padding(
          padding: const EdgeInsets.only(top: 30.0),
          child: Visibility(
            visible: true,
            child: TextButton(
              onPressed: () {
                if (!ifNext && !isTeacherOrSchoolAdmin) {
                  showSnackMsg("Please finish current page word quiz".tr);
                  // Get.snackbar(
                  //     'Message'.tr, "Please finish current page word quiz".tr,
                  //     backgroundColor: Get.isDarkMode
                  //         ? AppTheme.colors.darkTheme1
                  //         : Get.theme.primaryColorDark,
                  //     colorText: Get.theme.primaryColorLight,
                  //     snackPosition: SnackPosition.BOTTOM);
                  return;
                }
                setState(() {
                  controller.currWordQuizPage++;
                  note = '';
                  // shownext = false;
                });
              },
              child: Text(
                "Next".tr,
                style: const TextStyle(
                  fontSize: 18.0,
                ),
              ),
              style: ButtonStyle(
                backgroundColor:
                    MaterialStateProperty.all(Get.theme.primaryColorDark),
                foregroundColor: MaterialStateProperty.all(Get.isDarkMode
                    ? Colors.black
                    : Get.theme.primaryColorLight),
              ),
            ),
          ),
        ),
      );
    }

    return Scaffold(
        backgroundColor: Get.isDarkMode ? Color(0xff212121) : Colors.white,
        appBar: AppBar(
          title: Container(
            width: double.infinity,
            height: 45.0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(title.tr),
                SizedBox(width: 6),
                if (note != '')
                  MouseRegion(
                      cursor: SystemMouseCursors.click,
                      child: GestureDetector(
                        child: Icon(Icons.question_mark,
                            color: Colors.white, size: 21.0),
                        onTap: () {
                          showGeneralDialog(
                              context: context,
                              transitionDuration: Duration(milliseconds: 400),
                              pageBuilder: (bc, ania, anis) {
                                return SimpleAlertDialog(
                                    title: '', message: note.tr);
                              });
                        },
                      )),
              ],
            ),
          ),
        ),
        body: lastPage == false
            ? SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Column(children: children))
            : SafeArea(
                child: Stack(children: <Widget>[
                //CENTER -- Blast
                Visibility(
                  child: FireWorks(),
                  visible: firework,
                ),
              ])));
  }
}
